<template>
  <PageWrapper>
    <a-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @advanced="actionRef.redoHeight()" />
    </a-card>
    <a-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :row-selection="rowSelection"
        :request="loadDataTable"
        row-key="id"
        ref="actionRef"
        @select="handleSelect"
        @select-all="handleSelectAll"
      >
        <template #index="scoped">
          {{ scoped.rowIndex + 1 }}
        </template>
        <template #isUse="{ record }">{{ record.isUse == 1 ? '启用' : '禁用' }}</template>
        <template #tableTitle>
          <a-space>
            <a-button type="primary" @click="addAccountsHandle">新建用户</a-button>
            <a-button type="primary" @click="batchDeleteHandle">批量删除</a-button>
          </a-space>
        </template>
        <template #actions="{ record }">
          <a-button
            @click="deleteAccountHandle(record.id)"
            style="margin: 0 10px"
            type="primary"
            size="mini"
          >
            删除
          </a-button>
          <a-button
            style="margin: 0 10px"
            type="primary"
            size="mini"
            @click="toggleAccountHandle(record)"
          >
            {{ record.isUse == 0 ? '启用' : '禁用' }}
          </a-button>
        </template>
        <template #toolbar>
          <a-button type="primary" @click="actionRef.reload()">刷新数据</a-button>
        </template>
      </BasicTable>
    </a-card>
    <a-modal width="40%" title="新增商户账号" v-model:visible="showModal">
      <a-upload @success="progessHandle" :custom-request="uploadRequest">
        <template #upload-button>
          <div class="box-item">
            <div class="box-btn">
              <a-button @click="downloadTemplate" type="primary">
                <template #icon>
                  <icon-download />
                </template>
                下载模板
              </a-button>
            </div>
            <div>
              <p class="box-text">点击或者拖拽表格到此处</p>
            </div>
          </div>
        </template>
        <template #upload-item>
          <span></span>
        </template>
      </a-upload>
    </a-modal>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { getAccountList, delAccount, toggleAccount } from '@/api/business/account-list';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { PageWrapper } from '@/components/Page';
  import { BasicColumn, BasicTable } from '@/components/Table';
  import { ref, reactive } from 'vue';
  import { useGlobSetting } from '@/hooks/setting';
  import { downloadByData } from '@/utils/file/download';
  import { Message, Notification } from '@arco-design/web-vue';
  import { uploadBusinessFile } from '@/api/business/index';
  import { addTimestampUrl } from '@/utils/urlUtils';

  const globSetting = useGlobSetting();
  const { apiUrl, urlPrefix1, exportUrl } = globSetting;
  const uploadURL = apiUrl + urlPrefix1;
  const schemas: FormSchema[] = [
    {
      field: 'account',
      component: 'Input',
      label: '商户账号',
      componentProps: {
        allowClear: true,
        placeholder: '请输入商户账号',
      },
    },
    {
      field: 'isUse',
      component: 'Select',
      label: '状态',
      componentProps: {
        allowClear: true,
        placeholder: '请选择状态',
        options: [
          {
            label: '禁用',
            value: 0,
          },
          {
            label: '启用',
            value: 1,
          },
        ],
        onChange: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: '序号',
      slotName: 'index',
      width: 70,
    },
    {
      title: '账号',
      dataIndex: 'mobile',
      width: 200,
    },
    {
      title: '状态',
      slotName: 'isUse',
      width: 200,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      width: 200,
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      width: 120,
    },
    {
      title: '操作',
      width: 110,
      slotName: 'actions',
      fixed: 'right',
    },
  ];
  const selectedRowsData = ref<any[]>([]);
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });

  const actionRef = ref();

  const [register, {}] = useForm({
    labelColProps: {
      span: 6,
    },
    wrapperColProps: {
      span: 18,
    },
    labelWidth: 90,
    // layout: 'inline',
    rowProps: { gutter: [8, 8] },
    colProps: {
      xs: 24,
      sm: 24,
      md: 12,
      lg: 8,
      xl: 6,
    },
    schemas,
  });

  const tableData = ref();
  const loadDataTable = async (res) => {
    const { pageSize, page } = res;
    const response = await getAccountList(
      { ...res, pageSize: pageSize, pageNum: page },
      { pageSize: pageSize, pageNum: page },
    );
    tableData.value = response.list;
    return {
      totalCount: response.totalCount,
      list: response.list,
    };
  };

  function handleSubmit(values: Recordable) {
    if (values) {
      actionRef.value.reload(values);
    }
  }

  const deleteAccountHandle = async (ids: string) => {
    await delAccount({ ids });
    Message.success('删除成功');
    handleSubmit({});
  };

  const toggleAccountHandle = async (row: Recordable) => {
    const response = await toggleAccount({ id: row.id }, { isUse: row.isUse == 1 ? 0 : 1 });
    console.log(response);
    actionRef.value.reload();
  };

  const showModal = ref(false);

  const addAccountsHandle = () => {
    showModal.value = true;
  };
  const batchDeleteHandle = () => {
    if (selectedRowsData.value.length == 0) {
      Message.warning('请先选择数据');
      return;
    }
    delAccount({ ids: selectedRowsData.value.map((item) => item.id).join(',') }).then(() => {
      Message.success('删除成功');
      handleSubmit({});
    });
  };

  const downloadTemplate = () => {
    window.location.href = addTimestampUrl(`${exportUrl}商户账号模板xlsx.xlsx`);
  };
  const progessHandle = () => {};

  const handleSelect = (rowKeys) => {
    selectedRowsData.value = tableData.value.filter((item: any) => {
      return rowKeys.includes(item.id);
    });
  };
  const handleSelectAll = (checked) => {
    selectedRowsData.value = checked ? tableData.value : [];
  };

  const uploadRequest = (fileData) => {
    return uploadBusinessFile({
      url: uploadURL + '/account/importExcel',
      file: fileData.fileItem.file,
    }).then((res) => {
      const reader = new FileReader();
      reader.readAsText(res.data, 'utf-8');
      reader.onload = function () {
        try {
          const response = JSON.parse(reader.result as string);
          if (response.msg) {
            if (response.code == 200) {
              Notification.success({
                title: '操作成功',
                content: `上传成功`,
                closable: true,
                duration: 0,
              });
            } else {
              Notification.error({
                title: '操作失败',
                content: response.msg,
                closable: true,
                duration: 0,
              });
            }
          }
        } catch (err) {
          downloadByData(res.data, `商户账号上传结果.xlsx`);
        }
        showModal.value = false;
      };
    });
  };
</script>

<style lang="less" scoped>
  :deep(.arco-picker) {
    width: 100% !important;
  }
  :deep(.arco-upload-wrapper-type-text, .arco-arco-upload-wrapper) {
    display: none;
  }
  .order-box {
    padding: 45px;
    width: 1100px;
    margin: 0 auto;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    justify-content: space-between;
    row-gap: 20px;
  }

  .box-item {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    width: 300px;
    height: 233px;
    border-radius: 20px;
    background: #d8d8d8;
  }

  .box-btn {
    position: absolute;
    top: 10px;
    right: 10px;
  }

  .box-text {
    font-size: 18px;
    font-weight: 600;
    line-height: 24px;
    text-align: center;
    color: #434141;
  }
</style>
